

const convert = list => {
  // 三步走
  // 保存映射关系
  let map = new Map()
  list.forEach(el => {
    map.set(el.id, el)
  })

  // 建立父子连接关系
  list.forEach(el => {
    let parent = map.get(el.parentId)
    if (!parent) {
      // 无父节点，当前节点为根节点，则添加children属性
      el.children = []
      return
    }
    if (parent.children) {
      parent.children.push(el)
    } else {
      parent.children = [el]
    }
  })
  let res = []
  for (let i = 0; i < list.length; i++) {
    if (list[i].parentId === 0)
      res.push(list[i])
  }
  console.log(res);
  return res
};
let list = [
  { id: 1, name: '部门A', parentId: 0 },
  { id: 2, name: '部门B', parentId: 0 },
  { id: 3, name: '部门C', parentId: 1 },
  { id: 4, name: '部门D', parentId: 1 },
  { id: 5, name: '部门E', parentId: 2 },
  { id: 6, name: '部门F', parentId: 3 },
  { id: 7, name: '部门G', parentId: 2 },
  { id: 8, name: '部门H', parentId: 4 }
];
// console.log(JSON.stringify(convert(list)))
let tree = [{ "id": 1, "name": "部门A", "parentId": 0, "children": [{ "id": 3, "name": "部门C", "parentId": 1, "children": [{ "id": 6, "name": "部门F", "parentId": 3 }] }, { "id": 4, "name": "部门D", "parentId": 1, "children": [{ "id": 8, "name": "部门H", "parentId": 4 }] }] }, { "id": 2, "name": "部门B", "parentId": 0, "children": [{ "id": 5, "name": "部门E", "parentId": 2 }, { "id": 7, "name": "部门G", "parentId": 2 }] }]
function _convert(tree, res = []) {
  let attrList = Object.keys(tree[0])
  attrList = attrList.filter(item => item !== 'children')
  for (let i = 0; i < tree.length; i++) {
    let obj = {}
    attrList.forEach(key => {
      obj[key] = tree[i][key]
    })
    if (tree[i].children) {
      _convert(tree[i].children, res)
    }
    res.push(obj)
  }
  return res
}

console.log(_convert(tree))